default_platform(:ios)

platform :ios do

  desc "Bump Build Number"
  lane :bump_build_number do
    fetch_api_key()

    version_string = get_version_number(xcodeproj: "./Runner.xcodeproj")
    version_parts = version_string.split(".")

    # Remove last digit if necessary
    if version_parts.length > 3
      version_parts.pop
    end

    new_version = version_parts.join(".")

    increment_version_number(
      version_number: new_version,
      xcodeproj: "./Runner.xcodeproj"
    )
    increment_build_number(
      build_number: latest_testflight_build_number + 1,
      xcodeproj: "./Runner.xcodeproj"
    )
  end

  desc "Build Release"
  lane :build_release do

    setup_ci

    disable_automatic_code_signing

    sync_code_signing(
      type: "development",
      readonly: true,
      app_identifier: ["io.sentry.flutter.sample"]
    )

    sync_code_signing(
      type: "appstore",
      readonly: true,
      app_identifier: ["io.sentry.flutter.sample"]
    )

    update_project_provisioning(
      xcodeproj: "Runner.xcodeproj",
      target_filter: "Runner",
      profile: ENV["sigh_io.sentry.flutter.sample_appstore_profile-path"],
      build_configuration: "Release"
    )

    build_app(
      workspace: "Runner.xcworkspace",
      scheme: "Runner",
      configuration: "Release",
      clean: true,
      include_symbols: true,
      export_method: "app-store",
      output_directory:"./build/",
      export_options: {
        method: "app-store",
        provisioningProfiles: {
          "io.sentry.flutter.sample" => ENV["sigh_io.sentry.flutter.sample_appstore_profile-name"]
        }
      },
      codesigning_identity: ENV["sigh_io.sentry.flutter.sample_appstore_certificate-name"],
      output_name: "sentry_flutter_sample.ipa"
    )

    delete_keychain(
      name: "fastlane_tmp_keychain"
    ) unless is_ci
  end

  desc "Upload to TestFlight"
  lane :upload_testflight do
    fetch_api_key()
    testflight(
      skip_waiting_for_build_processing: true,
      ipa: "./build/sentry_flutter_sample.ipa"
    )
  end

  desc "Fetch ASC API Key"
  lane :fetch_api_key do
    app_store_connect_api_key(
      key_id: ENV["APP_STORE_CONNECT_KEY_ID"],
      issuer_id: ENV["APP_STORE_CONNECT_ISSUER_ID"],
      key_content: ENV["APP_STORE_CONNECT_KEY"]
    )
  end
end
